const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");


http.createServer((req,res)=>{
    if(req.url != "/favicon.ico"){
        const urlObj = url.parse(req.url);
        if(urlObj.pathname === "/api"){
            ajaxHandle(req,res);
        }else{
            fsHandle(req,res);
        }
    }
}).listen("81",()=>{
    console.log("服务器开启成功，http://localhost:81")
})



function ajaxHandle(req,res){
    let data = "";
    req.on("data",(chunk)=>{
        data += chunk
    });
    req.on("end",()=>{
        // console.log(data)
        if(data){
            data = qs.parse(data);
        }else{
            data = url.parse(req.url,true).query;
        }
        if(data.type === "login"){
            login(req,res,data)
        }else if(data.type === "register"){
            register(req,res,data)
        }
    })
}

function login(req,res,data){
    let i = 0;
    const onoff = userMsg.some((val,idx)=>{
        i = idx;
        return val.user === data.user;
    })
    let msg = null;
    if(onoff){
        if(userMsg[i].pass === data.pass){
            // 成功
            msg = {state:1,msg:"登录成功"}
            userMsg[i].state = 1;
        }else{
            // 不匹配
            msg = {state:2,msg:"用户名密码不匹配"}
        }
    }else{
        // 用户名不存在
        msg = {state:3,msg:"用户名不存在"}
    }
    res.write(JSON.stringify(msg));
    res.end();
}

let userMsg = [];
// [{user:"admin",pass:123456,state:0},{},{},...]

function register(req,res,data){
    const onoff = userMsg.some((val,idx)=>{
        return val.user === data.user;
    })
    let msg = null;
    if(onoff){
        // 用户名重复
        msg = {state:2,msg:"用户名重复"};
    }else{
        userMsg.push({
            user:data.user,
            pass:data.pass,
            state:0
        })
        // 注册成功
        msg = {state:1,msg:"注册成功"};
    }
    res.write(JSON.stringify(msg));
    res.end();
}


function fsHandle(req,res){
    const urlObj = url.parse(req.url)
    fs.readFile("./../static"+urlObj.pathname,(err,data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}